package com.yn.iotxiao.Utils.File;

import com.alibaba.fastjson.JSONObject;
import com.yn.iotxiao.Utils.JsonHelper;
import com.yn.iotxiao.Utils.StringUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

public class FileHelp {

    public static JSONObject saveWithFile(MultipartFile file, String ip) {
        File toFile = null;
        /*获取文件原名称*/
        String originalFilename = file.getOriginalFilename();
        /*获取文件格式*/
        String fileFormat = originalFilename.substring(originalFilename.lastIndexOf("."));

        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        toFile = new File(Paths.get(System.getProperty("user.dir") + "/static/face") + File.separator + originalFilename);

        String absolutePath = null;
        try {
            absolutePath = toFile.getCanonicalPath();

            /*判断路径中的文件夹是否存在，如果不存在，先创建文件夹*/
            String dirPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            InputStream ins = file.getInputStream();

            inputStreamToFile(ins, toFile);
            ins.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return JsonHelper.create("url","http://"+ ip +"/api" + absolutePath,"path",absolutePath);

    }
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
